package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@WebFilter("/*")
public class ServiceFilter implements Filter {
    private static final int MAX_COUNT = 5;
    private AtomicInteger filterCount = new AtomicInteger(0);

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //your  code....
        System.out.println("before" + filterCount);
        if (filterCount.get() > MAX_COUNT) {
            //请求个数太多，跳转到排队页面
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            //请求个数加1
            filterCount.incrementAndGet();
            chain.doFilter(request, response);
            //访问结束，请求个数减1
            filterCount.decrementAndGet();
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}